package com.rongzhe.house.manager;

import com.rongzhe.house.entity.ResponseEntityVo;
import com.rongzhe.house.entity.voo.Tag;
import com.rongzhe.house.internet.DataListener;
import com.rongzhe.house.internet.InternetRequestWorker;
import com.rongzhe.house.internet.ResponseDispatcher;
import com.rongzhe.house.internet.net.TagInterface;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by huang on 2018/1/1.
 */

public class TagManager {
    private TagManager() {
    }
    private static TagManager sInstance;
    public static TagManager getInstance() {
        if (sInstance == null) {
            sInstance = new TagManager();
        }
        return sInstance;
    }
    private Map<String, List<Tag>> mAllTags = new HashMap<>();

    public void getAllTags(DataListener<List<Tag>> listener) {
        InternetRequestWorker.getInstance().asyncNetwork(
                InternetRequestWorker.getInstance()
                        .create(TagInterface.class).getAll(), new ResponseDispatcher(listener) {
                    @Override
                    public void handleSuccess(ResponseEntityVo data) {
                        if (data.success()) {
                            List<Tag> tags = (List<Tag>) data.getData();
                            addTagItems(tags);
                        }
                    }
                });
    }

    public void getByType(String type, DataListener<List<Tag>> listener) {
        InternetRequestWorker.getInstance().asyncNetwork(
                InternetRequestWorker.getInstance()
                        .create(TagInterface.class).getTagListByType(type),
                new ResponseDispatcher(listener) {
                    @Override
                    public void handleSuccess(ResponseEntityVo data) {
                        if (data.success()) {
                            List<Tag> tags = (List<Tag>) data.getData();
                            addTagItems(tags);
                        }
                    }
                });
    }

    public void getTageByType(String type, DataListener<List<Tag>> listener) {
        if (mAllTags.get(type) == null) {
            getByType(type, listener);
            return;
        }
        listener.onSuccess(mAllTags.get(type), null);
    }

    private void addTagItems(List<Tag> tags) {
        if (tags == null) {
            return;
        }
        for(Tag tag : tags) {
            List<Tag> addedTags = mAllTags.get(tag.getType());
            if (addedTags == null) {
                addedTags = new ArrayList<>();
                mAllTags.put(tag.getType(), addedTags);
            }
            addedTags.add(tag);
        }
    }

}
